<template>
  <div class="business-plan-add-view view-container">

    <header-module
      left-custom
      padding
    >
      <template #left-con>
        <div>
          <span style="font-size: 16px; margin-right: 20px">新建精细招商规划</span>
        </div>
      </template>

      <template #btn>
        <el-button
          class="main-btn"
          size="small"
          @click="onBack"
        >返回</el-button>
        <el-button
          :disabled="isSave"
          class="main-btn"
          size="small"
          type="primary"
          @click="onSave"
        >保存</el-button>
        <el-button
                :disabled="isSave"
          class="main-btn"
          size="small"
          type="primary"
          @click="onAudit"
        >提交审核</el-button>
      </template>

    </header-module>

    <div class="main-content">

      <el-tabs
        v-model="activeName"
        :before-leave="beforeLeave"
        @tab-click="handleClick"
      >
        <el-tab-pane
          label="基本信息"
          name="first"
        />
        <el-tab-pane
          label="招商终端明细"
          name="second"
        />
      </el-tabs>

      <information
        v-if="activeName == 'first'"
        ref="refInformation"
        :citys="citys"
        :datas="datas.planInfo"
        :disabled="disabled"
        :list="datas.planDetail"
        @save="dataSave"
      />

      <termina-view
        v-else-if="activeName == 'second'"
        ref="refTermina"
        v-model:deletes="deletes"
        v-model:list="datas.planDetail"
        :area="area"
        :datas="datas"
        :plan-id="datas.planInfo.id"
        @deleteData="deleteData"
      />
    </div>

  </div>
</template>

<script>
import areas from '@/utils/area.js'
import areaCode from '@/utils/areaCode'
import { getScreenAreaData } from '@/utils/areaFuc'
import {
  defineAsyncComponent,
  defineComponent,
  getCurrentInstance,
  inject,
  onBeforeMount,
  reactive,
  ref,
  toRefs,
} from 'vue'
import { useRoute, useRouter } from 'vue-router'

export default defineComponent({
  name: 'AddPlan',
  components: {
    information: defineAsyncComponent(() =>
      import('./modules/information.vue')
    ),
    terminaView: defineAsyncComponent(() =>
      import('./modules/terminaView.vue')
    ),
  },
  setup() {
    var oldInfo = ref('')
    var oldDetail = ref('')
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    var disabled = ref(true)
    var citys = ref([])

    var data = reactive({
      datas: {
        planInfo: {
          selectName: '',
          planType: '1',
          areas: [],
          productId: 0,
          chanceId: '',
          guidingPrice: '',
          region: [],
          terminalPrice: '',
          files: [],
          date1: '',
          date: '',
          chanceRegion: [],
          isTerminalPrice:true,
        },
        planDetail: [],
      },
      ChanceInfo: {},
      area: [],
      deletes: [],
      refInformation: null,
      refTermina: null,
      isDelete: false,
      isSave:false,
    })

    const router = useRouter()
    const route = useRoute()

    var activeName = ref('first')

    onBeforeMount(() => {
      if (route.query.chance_id) {
        data.datas.chance_id = route.query.chance_id
      }
      if (route.query.id) {
        getData(route.query.id)
      } else {
        if (data.datas.chance_id) {
          api.chance.CHANCE_DETAIL(route.query.chance_id).then((res) => {
            if (!res.code && res.data) {
              data.ChanceInfo = res.data.ChanceInfo

              data.datas.planInfo.chanceId = data.ChanceInfo.id
              data.datas.planInfo.chanceName = data.ChanceInfo.chanceName
              data.area = getScreenAreaData(data.ChanceInfo.region)
              data.datas.planInfo.chanceRegion = data.ChanceInfo.region
              data.datas.planInfo.region = data.ChanceInfo.region
              // data.datas.planInfo.areas = currentInstance.proxy.getCascaderAreaData(data.datas.planInfo.region)
              data.datas.planInfo.accessMode = data.ChanceInfo.accessMode
              data.datas.planInfo.terminalType = data.ChanceInfo.terminalType
              data.datas.planInfo.priceProperty =
                data.ChanceInfo.priceProperty + ''
              // data.datas.planInfo.productPriceId = data.ChanceInfo.productPriceId
              // data.datas.planInfo.terminalPrice = data.ChanceInfo.terminalPrice + ''
              data.datas.planInfo.expireTime = data.ChanceInfo.expireTime

              data.datas.planInfo.productId = data.ChanceInfo.productId
              data.datas.planInfo.productName = data.ChanceInfo.productName
              data.datas.planInfo.productPopularName =
                data.ChanceInfo.productPopularName
              data.datas.planInfo.packSpecs = data.ChanceInfo.packSpecs
              data.datas.planInfo.approvalNumber =
                data.ChanceInfo.approvalNumber
              data.datas.planInfo.sellUnit = data.ChanceInfo.sellUnit

              citys.value = getScreenAreaData(data.ChanceInfo.region)
            }

            setTimeout(() => {
              disabled.value = false
            }, 100)
          })
        } else {
          disabled.value = false
          citys.value = areas
        }
      }
    })

    const getChance = (id) => {
      api.chance.CHANCE_DETAIL(id).then((res) => {
        if (!res.code && res.data) {
          citys.value = getScreenAreaData(res.data.ChanceInfo.region)
        }
      })
    }

    const getTerminalPrice = () => {
      if (!data.datas.planInfo.productPriceId) return
      api.product.PRODUCT_PRICE_DETAIL(data.datas.planInfo.productPriceId).then((res) => {
        if (!res.code) {
          if (res.data.productPriceStrategy.terminalType == 'all'){
            data.datas.planInfo.isTerminalPrice = true
          }else{
            data.datas.planInfo.isTerminalPrice = false
          }
          oldInfo.value = JSON.stringify(data.datas.planInfo)
        }
      })
    }

    const getData = (id) => {
      api.plan.GET_PLAN_DETAIL({ id: id }).then((res) => {
        if (!res.code) {
          if (data.datas.planInfo.areas.length) {
            res.data.plan.planInfo.areas = data.datas.planInfo.areas
          }
          data.datas = res.data.plan
          data.datas.planInfo.selectName = data.datas.planInfo.chanceName
          if (data.datas.planInfo.chanceId) {
            // getChance(data.datas.planInfo.chanceId)
            citys.value = getScreenAreaData(data.datas.planInfo.chanceRegion)
          } else {
            citys.value = areas
            getTerminalPrice()
          }
          data.datas.planInfo.date = data.datas.planInfo.expireTime
          if (data.datas.planInfo.terminalPrice) {
            data.datas.planInfo.terminalPrice =
              data.datas.planInfo.terminalPrice + ''
          }
          if (data.datas.planInfo.guidingPrice) {
            data.datas.planInfo.guidingPrice =
              data.datas.planInfo.guidingPrice + ''
          }

          if (!data.datas.planInfo.files) {
            data.datas.planInfo.files = []
          }

          data.datas.planDetail.forEach((item) => {
            if (item.sellEarnestMoney) {
              item.salesStr = item.sellEarnestMoney
            }
            if (item.devEarnestMoney) {
              item.exploitPrice = item.devEarnestMoney
            }
            if (!item.expireTime) {
              item.expireTime = ''
            }

            if (item.terProvinceName) {
              item.area = item.terProvinceName
            }
            if (item.terCityName) {
              item.area = item.area + '/' + item.terCityName
            }
            if (item.terAreaName) {
              item.area = item.area + '/' + item.terAreaName
            }
            item.isEdit = false
          })

          data.area = getScreenAreaData(res.data.plan.planInfo.region)
          // data.datas.planInfo.areas = getCascaderAreaData1(res.data.plan.planInfo.region)
          oldInfo.value = JSON.stringify(data.datas.planInfo)
          oldDetail.value = JSON.stringify(data.datas.planDetail)

          if (data.refTermina) {
            data.refTermina.refreshData()
          }
          setTimeout(() => {
            disabled.value = false
          }, 100)
        }
      })
    }

    const dataSave = () => {
      oldInfo.value = JSON.stringify(data.datas.planInfo)
    }

    const getCascaderAreaData1 = (arr) => {
      let list = []

      for (let i = 0; i < arr.length; i++) {
        const item = arr[i]

        if (item.level == 3) {
          const pCode = item.regionCode.slice(0, 2) + '0000'
          const cCode = item.regionCode.slice(0, 4) + '00'

          list.push([pCode, cCode, item.regionCode])
        } else {
          list = list.concat(areaCode[item.regionCode])
        }
      }

      return list
    }

    const onBack = () => {
      router.back()
    }

    const handleClick = () => {
      data.area = getScreenAreaData(data.datas.planInfo.region)
    }

    const saveData = () => {
      return new Promise((resolve, reject) => {
        const edit = {
          planInfo: data.datas.planInfo,
          planDetail: data.datas.planDetail,
          deleteDetailIds: data.deletes,
          updateType: activeName.value == 'first' ? 1 : 2,
        }
        data.isSave = true
        api.plan
          .PLAN_EDIT(edit)
          .then((res) => {
            data.isSave = false
            if (!res.code) {
              resolve(res.data)
            } else {
              reject(res)
            }
          })
          .catch((err) => {
            data.isSave = false
            reject()
          })
      })
    }

    const onSave = () => {
      console.log(data.datas.planInfo)

      data.datas.planInfo.guidingPrice = Number(
        data.datas.planInfo.guidingPrice
      )
      data.datas.planInfo.terminalPrice = Number(
        data.datas.planInfo.terminalPrice
      )
      if (activeName.value == 'first') {
        data.refInformation.validate().then(() => {
          save()
        })
      } else {
        // data.refTermina.validate().then(()=>{
        //
        // })
        save()
      }
    }

    const deleteData = () => {
      data.isDelete = true
      onSave()
    }

    const save = () => {
      data.datas.planDetail.forEach((item) => {
        item.minSale = Number(item.minSale)
      })
      if (route.query.id || data.datas.planInfo.id) {
        // 编辑
        saveData()
          .then((a) => {
            // if (activeName.value == "first"){
            //     oldInfo.value = JSON.stringify(data.datas.planInfo)
            // }else {
            //     oldDetail.value = JSON.stringify(data.datas.planDetail)
            // }
            getData(data.datas.planInfo.id)
            if (data.isDelete) {
              data.isDelete = false
            } else {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: '保存成功',
              })
            }
          })
          .catch((res) => {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: res.msg,
            })
          })
      } else {
        data.isSave = true
        // 新建
        api.plan.PLAN_CREATE(data.datas).then((res) => {
          data.isSave = false
          if (!res.code) {
            getData(res.data.plan.id)
            // data.datas.planInfo.id = res.data.plan.id
            // oldInfo.value = JSON.stringify(data.datas.planInfo)
            oldDetail.value = JSON.stringify(data.datas.planDetail)
            currentInstance.proxy.customMessage({
              type: 'success',
              message: '新建成功',
            })
          } else {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: res.msg,
            })
          }
        }).catch(()=>{
          data.isSave = false
        })
      }
    }

    const beforeLeave = (name) => {
      console.log(name)
      // currentInstance.proxy.getServeAreaData()

      if (name == 'first') {
        const p_detail = JSON.stringify(data.datas.planDetail)
        if (p_detail != oldDetail.value) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请先保存数据',
          })
          return false
        }
      } else if (name == 'second') {
        if (data.datas.planInfo.id) {
          const p_info = JSON.stringify(data.datas.planInfo)

          if (p_info != oldInfo.value) {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: '请先保存数据',
            })
            return false
          }
        } else {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请先保存数据',
          })
          return false
        }
      }
    }

    const onAudit = () => {
      console.log(data)
      data.datas.planInfo.guidingPrice = Number(
        data.datas.planInfo.guidingPrice
      )
      data.datas.planInfo.terminalPrice = Number(
        data.datas.planInfo.terminalPrice
      )

      currentInstance.proxy
        .alertBox({
          message: '是否提交审核该规划？',
          title: '审核',
        })
        .then(() => {
          if (activeName.value == 'first') {
            data.refInformation.validate().then(() => {
              if (checkTermina()) {
                saveData().then((data) => {
                  audit()
                })
              }
            })
          } else {
            data.refTermina.validate().then(() => {
              saveData().then((data) => {
                audit()
              })
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    }

    const checkTermina = () => {
      if (!data.datas.planDetail.length) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请添加终端',
        })
        return false
      } else {
        for (let i = 0; i < data.datas.planDetail.length; i++) {
          const ter = data.datas.planDetail[i]
          if (ter.validStatus) {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: ter.terminalName + '不符合此规划规则,请删除',
            })
            return false
          }
          if (!ter.expireTime) {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: '请选择' + ter.terminalName + '终端的截止日期',
            })
            return false
          }
          if (!ter.devEarnestMoney) {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: '请输入' + ter.terminalName + '终端的开发保证金',
            })
            return false
          }
        }

        return true
      }
    }

    const audit = () => {
      api.plan.PLAN_CHECK_COMMIT({ id: data.datas.planInfo.id }).then((res) => {
        if (res.code) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        } else {
          currentInstance.proxy.customMessage({
            type: 'success',
            message: '提交成功',
          })
          router.back()
        }
      })
    }

    return {
      activeName,
      ...toRefs(data),
      disabled,
      citys,

      onBack,
      handleClick,
      onSave,
      beforeLeave,
      onAudit,
      dataSave,
      deleteData,
    }
  },
})
</script>

<style scoped>
</style>
